package com.wisdom.server.rpc.netty;

import com.wisdom.core.netty.handler.coder.FrameDecoder;
import com.wisdom.core.netty.handler.coder.FrameEncoder;
import com.wisdom.core.netty.handler.server.RpcRequestDecoder;
import com.wisdom.core.netty.handler.server.RpcResponseEncoder;
import com.wisdom.server.config.ServerRpcConfig;
import com.wisdom.server.handler.RpcRequestHandler;
import com.wisdom.server.rpc.RpcServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.NettyRuntime;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.concurrent.UnorderedThreadPoolEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @description: <Netty rpc server run>
 * @author: Leo
 * @date:2021-08-22 12:45
 */
@Component
@Slf4j
public class NettyServer implements RpcServer {

    @Autowired
    private ServerRpcConfig serverRpcConfig;

    @Override
    public void rpcServerStart() {
        //核心线程  用于绑定服务端 ip和端口
        EventLoopGroup boss = new NioEventLoopGroup(1, new DefaultThreadFactory("boss-"));
        //IO 线程池  核心线程数默认为0   会根据服务器CPU核数 * 2 创建
        EventLoopGroup worker = new NioEventLoopGroup(0, new DefaultThreadFactory("worker-"));
        //工作线程池 reactor 主从工作线程
        UnorderedThreadPoolEventExecutor business = new UnorderedThreadPoolEventExecutor(NettyRuntime.availableProcessors() * 2,
                new DefaultThreadFactory("business-"));

        RpcRequestHandler rpcRequestHandler = new RpcRequestHandler();
        //启动Netty 服务端
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    //option 给 NioServerSocketChannel 设置     等待队列 如果连接过多 会进入队列进行等待
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //childOption 给 SocketChannel设置   禁用TCP算法 避免数据发送延迟问题
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    //开启底层的 TCP KEEPALIVE
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //给pipeline 添加日志
                            //pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                           /*
                                handler 处理顺序  默认放置在IO线程池

                                接收请求参数： Inbound 类型数据
                                先将Inbound的数据解码为 ByteBuf
                                再将ByteBuf 数据转换为 RpcRequest
                                然后交由处理器匹配API 进行业务处理

                                响应数据： outBound 类型数据
                                先将 RpcResponse编码为 ByteBuf
                                再将 ByteBuf 转换为 outBound的响应数据
                           */
                            //outBound 处理
                            pipeline.addLast(new FrameEncoder());
                            pipeline.addLast(new RpcResponseEncoder());

                            //Inbound 处理
                            pipeline.addLast("FrameDecoder",new FrameDecoder());
                            pipeline.addLast("RpcRequestDecoder",new RpcRequestDecoder());
                            //请求处理器  该处理器放置在 工作线程中
                            pipeline.addLast(business,"RpcRequestHandler",rpcRequestHandler);
                        }
                    });
            //绑定端口
            ChannelFuture future = bootstrap.bind(serverRpcConfig.getServerPort()).sync();
            log.info("rpc server startUp success");
            //监听端口关闭
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("rpc server start error,msg= {}", e.getMessage());
        } finally {
            //shutdown
            boss.shutdownGracefully();
            worker.shutdownGracefully();
            business.shutdownGracefully();
        }
    }

}
